<script setup lang="ts">
import {
  defineProps,
  onMounted,
  ref,
  withDefaults,
} from 'vue'
import {
  DeleteFilled,
  EditPen,
  Message,
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import {
  useUserDeletePostByAdminApi,
  useUserDeletePostByCommonApi,
  useUserDeletePostByModeratorApi,
  useUserGetAllApi,
} from '@/api/user'
import { ElMessage, ElDialog } from 'element-plus'
// 引入 useRouter 函数
import { useRouter } from 'vue-router'
import { usePostGetCommentByPostIdApi } from '@/api/post'
// 引入发送邮件的 API
import { useUserSendEmailApi } from '@/api/user'

const commentCount = ref(0)
onMounted(() => {
  setTimeout(() => {
    usePostGetCommentByPostIdApi({
      id: props.postData.id,
    }).then((res) => {
      commentCount.value = res.data.data.length
    })
  }, 500)
})
// 定义删除帖子的方法
const handleDelete = (postId: number) => {
  const userStore = useUserStore()
  switch (userStore.user.role) {
    case 'common':
      useUserDeletePostByCommonApi({
        id: postId,
        userId: userStore.user.id,
      }).then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
      break
    case 'moderator':
      useUserDeletePostByModeratorApi({
        id: postId,
        userId: userStore.user.id,
      }).then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
      break
    case 'admin':
      useUserDeletePostByAdminApi({
        id: postId,
        userId: userStore.user.id,
      }).then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
      break
  }
  setTimeout(() => {
    window.location.reload()
  }, 500)
}

// 定义编辑帖子的方法
const router = useRouter()
const handleEdit = (postId: number) => {
  // 跳转到编辑页面
  router.push(`/post-edit/${postId}`)
}

// 定义 props 类型
const props = withDefaults(
  defineProps<{
    postData?: {
      cover: string
      username: string
      title: string
      desc: string
      publishTime: string
      commentCount: number
      id: number
      userId: number
    }
    permission?: {
      read: number
      comment: number
    }
  }>(),
  {
    postData: () => ({
      cover: 'null',
      username: 'John Doe',
      title: '这是一个示例帖子标题',
      desc: '这里是示例帖子的描述内容，包含一些相关信息。',
      publishTime: '2025-06-07 12:00:00',
      commentCount: 0,
      id: -1,
      userId: -1,
    }),
    permission: () => ({
      read: 0,
      comment: 0,
    }),
  },
)

const userStore = useUserStore()

// 定义对话框相关响应式变量
const dialogVisible = ref(false)
const emailTitle = ref('')
const emailContent = ref('')

// 显示对话框
const showDialog = () => {
  dialogVisible.value = true
}

// 定义用户类型
interface User {
  id: number
  email: string
  // 可根据实际返回数据添加其他字段
}

// 发送邮件
const sendEmail = async () => {
  if (
    !emailTitle.value.trim() ||
    !emailContent.value.trim()
  ) {
    ElMessage.warning('请填写邮件标题和内容')
    return
  }
  try {
    // 获取用户列表
    const res = await useUserGetAllApi()
    const user = res.data.data.find(
      (data: User) => data.id === props.postData.userId,
    )

    if (!user) {
      ElMessage.warning('未找到接收用户的邮箱信息')
      return
    }

    await useUserSendEmailApi({
      subject: emailTitle.value,
      text: emailContent.value,
      // 可以根据实际情况添加其他参数，如接收者 ID 等
      to: user.email,
    })
    ElMessage.success('邮件发送成功')
    dialogVisible.value = false
    emailTitle.value = ''
    emailContent.value = ''
  } catch (error) {
    ElMessage.error('邮件发送失败，请稍后重试')
    console.error('邮件发送失败:', error)
  }
}
</script>

<template>
  <div
    class="post flex"
    :class="{ 'has-mask': props.permission.read }"
  >
    <!-- 当 read 为 false 时显示蒙版 -->
    <div
      v-if="
        props.permission.read == 1 &&
        userStore.user.role == ''
      "
      class="mask"
    >
      <div class="hint">游客不可看</div>
    </div>
    <div class="left">
      <!-- 渲染封面图 -->
      <img
        class="cover"
        :src="props.postData.cover"
        alt="无封面"
      />
    </div>
    <div class="right">
      <!-- 渲染用户名 -->
      <div class="username">
        {{ props.postData.username }}
      </div>
      <!-- 渲染帖子标题，read 为 false 时禁止跳转 -->
      <RouterLink :to="`/post/${props.postData.id}`">
        <div class="title">{{ props.postData.title }}</div>
      </RouterLink>

      <div class="desc">{{ props.postData.desc }}</div>
      <!-- 新增帖子发布时间 -->
      <div class="time">
        {{ props.postData.publishTime }}
      </div>
      <!-- 新增互动信息，comment 为 false 时隐藏 -->
      <div class="interactions">
        <span class="comment">💬 {{ commentCount }}</span>
      </div>
    </div>
    <!-- 操作按钮 -->
    <div class="operation">
      <el-popconfirm
        v-if="
          props.postData.userId == userStore.user.id ||
          userStore.user.role == 'admin'
        "
        confirm-button-text="确认"
        cancel-button-text="取消"
        icon="el-icon-question"
        title="确定要删除该帖子吗？"
        @confirm="() => handleDelete(props.postData.id)"
      >
        <template #reference>
          <el-icon><DeleteFilled /></el-icon>
        </template>
      </el-popconfirm>
      <!-- 绑定编辑方法 -->
      <el-icon
        v-if="props.postData.userId == userStore.user.id"
        @click="() => handleEdit(props.postData.id)"
      >
        <EditPen />
      </el-icon>
      <!-- 点击图标显示对话框 -->
      <el-icon @click="showDialog">
        <Message />
      </el-icon>
      <!-- 邮件对话框 -->
      <ElDialog
        v-model="dialogVisible"
        title="发送邮件"
        width="50%"
      >
        <el-form>
          <el-form-item label="邮件标题">
            <el-input v-model="emailTitle" />
          </el-form-item>
          <el-form-item label="邮件内容">
            <el-input
              v-model="emailContent"
              type="textarea"
              :rows="5"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false"
              >取消</el-button
            >
            <el-button type="primary" @click="sendEmail"
              >发送</el-button
            >
          </span>
        </template>
      </ElDialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.post {
  position: relative; // 为操作按钮和蒙版提供定位参考
  display: flex;
  gap: 20px;
  padding-right: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin-bottom: 20px;
  height: 200px;
}

.has-mask {
  position: relative;
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3); /* 半透明黑色蒙版 */
  /* 添加磨砂效果 */
  -webkit-backdrop-filter: blur(5px);
  backdrop-filter: blur(5px);
  z-index: 10; /* 确保蒙版在内容上方 */
  cursor: not-allowed; /* 鼠标指针显示禁止符号 */
  .hint {
    margin-left: 500px;
  }
}

.operation {
  position: absolute; // 绝对定位
  top: 10px; // 距离顶部 10px
  right: 10px; // 距离右侧 10px
  display: flex;
  gap: 10px; // 按钮间间距
  z-index: 20; /* 确保操作按钮在蒙版上方 */
}

// 保持原有样式
.left {
  width: 200px;
  height: 200px;
}

.cover {
  margin: 2%;
  width: 96%;
  height: 96%;
  border-radius: 4px;
}

.right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.username {
  font-size: 14px;
  color: #666;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.desc {
  font-size: 14px;
  color: #999;
}

.time {
  font-size: 12px;
  color: #bbb;
}

.interactions {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #666;
}
</style>
